<template>
  <div id="app" class="odd-job-detail">
    <!-- 头部导航 -->
    <van-nav-bar
        left-text="返回"
        left-arrow
        @click-left="onClickBack"
    >
      <template slot="title"> <span>报工详情</span> </template>
    </van-nav-bar>

    <van-row type="flex" align="center">
      <van-col>
        <van-field label="临活名称:" size="large" readonly label-align="right" v-model="taskParams.jobName"/>
      </van-col>
      <van-col>
        <van-field label="创建时间:" size="large" readonly label-align="right" v-model="taskParams.createAt"/>
      </van-col>
      <van-col>
        <van-field label="发布人:" size="large" readonly label-align="right" v-model="taskParams.applicantName"/>
      </van-col>
    </van-row>

    <!-- 杂活任务详情表格 -->
    <div style="padding: 15px; height:78%;">
      <div>
        <van-row class="craft-row first" type="flex" justify="space-between" align="center">
          <van-col class="craft-row-col title"><span>员工</span></van-col>
          <van-col class="craft-row-col title datetime"><span>开工时间</span></van-col>
          <van-col class="craft-row-col title datetime"><span>完工时间</span></van-col>
          <van-col class="craft-row-col title opt"><span>操作</span></van-col>
        </van-row>
      </div>
      <div style="max-height: 94%; overflow: auto">
        <van-row v-show="row.optFlag != 3" class="craft-row" type="flex" justify="space-between" align="center" v-for="(row, index) in jobDetailData" :key="row.workerId">
          <van-col class="craft-row-col">
            <span> {{ row.workerName ? row.workerName : "&nbsp;"  }}</span>
          </van-col>
          <van-col class="craft-row-col" @click="showDateTimePopFn(row, 'startAt')">
            <span> {{ row.startAt ? row.startAt : "&nbsp;"  }}</span>
          </van-col>
          <van-col class="craft-row-col" @click="showDateTimePopFn(row, 'finishAt')">
            <span> {{ row.finishAt ? row.finishAt : "&nbsp;"  }}</span>
          </van-col>
          <van-col class="craft-row-col opt">
            <van-button type="danger" @click="delWorkerFn(index)">删除</van-button>
          </van-col>
        </van-row>
      </div>
    </div>
    <div style="display: flex; justify-content: center; align-items: center">
      <van-button type="info" style="width: 300px;font-size: 22px;margin-right: 30px;" @click="changeTaskDetailFn(false)">临时报工</van-button>
      <van-button type="primary" style="width: 300px;font-size: 22px;" @click="changeTaskDetailFn(true)">完成报工</van-button>
    </div>

    <van-popup v-model="showDateTimePop" round position="bottom">
      <van-datetime-picker
          type="datetime"
          title="选择完整时间"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="dateTimePickerFormatterFn"
          @confirm="dateTimeSelectConfirmFn"
      />
    </van-popup>


  </div>
</template>

<script>
import {getFloat, openWin, randomStr} from "@/utils/index";
import dayjs from "dayjs";
import { loadOddJobTaskDetailData, changeTaskDetail } from "@/views/odd-job/index";
import { getLogin, getRefreshToken } from "@/api/login";
import {getInfo, setInfo} from "../../../utils/auth";
import {checkInWorking} from "../index";

export default {
  name: "oddJobTask",
  data() {
    return {
      //会话更新
      sessionTimer: {},
      /* 扫码 */
      code: "",
      lastTime: "",
      nextTime: "",
      lastCode: "",
      nextCode: "",
      intervalFlag: false,

      /* 任务信息 从前面页面带过来 */
      taskParams: {
        jobName: "",
        createAt: "",
        applicantName: "",
      },

      /* 时间选择 */
      minDate: dayjs().subtract(7, "day").toDate(),
      maxDate: new Date(2025, 10, 1),
      showDateTimePop: false,
      curRow: null,
      curDateTimeField: "",

      //详情列表
      jobDetailData: [],

      //临时保存定时
      changeTaskDetailTimer: {}
    }
  },
  mounted() {
    let that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  watch: {
    // 监听扫码标记
    intervalFlag() {
      const that = this;
      setTimeout(() => {
        that.intervalFlag = false;
      }, 2000);
    },
  },
  methods: {
    initFn(that) {
      that.sessionTimer = setInterval(() => {
        that.onGetRefreshToken();
      }, 600000);
      // 监听页面消失的时候，关掉页面就可以了
      window.api.addEventListener({
        name: "viewdisappear",
      }, function () {
        clearInterval(that.sessionTimer);
        window.api.closeWin();
      });

      let pageParam = window.api.pageParam;
      Object.keys(pageParam).forEach(key => {
        that.taskParams[key] = pageParam[key];
      })
      window.addEventListener("keydown", that.onClickKeydown);

      that.loadOddJobTaskDetailDataFn();
    },
    // 刷新token
    onGetRefreshToken() {
      getRefreshToken({
        secret: getInfo().secret,
      },
      (res) => {
        setInfo(res);
      });
    },
    // 返回
    onClickBack() {
      openWin("odd-job-task");
    },
    // 监听事件 扫码
    onClickKeydown(e) {
      const that = this;
      const Toast = that.$toast({
        type: "loading",
        message: "二维码解析中",
        forbidClick: true,
        duration: 1000,
      });
      if (window.event) {
        // IE
        that.nextCode = e.keyCode;
      } else if (e.which) {
        // Netscape/Firefox/Opera
        that.nextCode = e.which;
      }
      if (e.which === 13) {
        if (that.code.length < 3) return; // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
        if (!that.intervalFlag) {
          that.intervalFlag = true;
          Toast.clear();
          let code = that.code.replace(/Shift/g, "");
          let loginIndex = code.indexOf(",type=login,");
          if (loginIndex != -1) {
            let infos = code.split(",type=login,");

            //清理之前的自动保存
            clearTimeout(that.changeTaskDetailTimer);

            if(infos[0] == getInfo().no) {
              let exists = that.jobDetailData.find(row => row.workerId == getInfo().userId);
              if(exists && exists.optFlag == 3) {
                exists.optFlag = 0;
              } else if(!exists) {
                that.checkInWorkingFn(getInfo().userId, () => {
                  that.jobDetailData.push({
                    workerId: getInfo().userId,
                    workerNo: getInfo().no,
                    workerName: getInfo().realName,
                    startAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                    optFlag: 1
                  });

                  //自动临时保存
                  that.changeTaskDetailTimer = setTimeout(() => {
                    that.changeTaskDetailFn(false);
                  }, 90000);
                });
              } else {
                that.$toast.fail("员工已存在");
              }
            } else {
              //登陆
              getLogin({
                no: infos[0],
                pwd: infos[1],
                platform: 2,
                captcha: randomStr(),
              }, res => {
                let exists = that.jobDetailData.find(row => row.workerId == res.userId);
                if(exists && exists.optFlag == 3) {
                  exists.optFlag = 0;
                } else if(!exists) {
                  that.checkInWorkingFn(res.userId, () => {
                    that.jobDetailData.push({
                      workerId: res.userId,
                      workerNo: res.userNo,
                      workerName: res.realName,
                      startAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                      optFlag: 1
                    });

                    //自动临时保存
                    that.changeTaskDetailTimer = setTimeout(() => {
                      that.changeTaskDetailFn(false);
                    }, 90000);
                  });
                } else {
                  that.$toast.fail("员工已存在");
                }
              });
            }
          } else {
            that.$toast.fail("员工二维码异常");
          }
        } else {
          that.$toast.fail("扫码过于频繁");
        }

        that.code = "";
        that.lastCode = "";
        that.lastTime = "";
        return;
      }
      that.nextTime = new Date().getTime();
      if (!that.lastTime && !that.lastCode) {
        console.log("扫码开始。。。");
        that.code += e.key;
      }
      if (
          that.lastCode &&
          that.lastTime &&
          that.nextTime - that.lastTime > 500
      ) {
        // 当扫码前有keypress事件时,防止首字缺失
        console.log("防止首字缺失。。。");
        that.code = e.key;
      } else if (that.lastCode && that.lastTime) {
        console.log("扫码中。。。");
        that.code += e.key;
      }
      that.lastCode = that.nextCode;
      that.lastTime = that.nextTime;
    },

    //时间选择
    dateTimePickerFormatterFn(type, val) {
      if (type === 'year') {
        return val + '年';
      } else if (type === 'month') {
        return val + '月';
      } else if (type === 'day') {
        return val + '日';
      } else if (type === 'hour') {
        return val + '时';
      } else if (type === 'minute') {
        return val + '分';
      }
      return val;
    },
    showDateTimePopFn(row, field) {
      let that = this;
      that.showDateTimePop = true;
      that.curRow = row;
      that.curDateTimeField = field;
    },
    //选中时间
    dateTimeSelectConfirmFn(value) {
      let that = this;
      that.showDateTimePop = false;
      that.curRow[that.curDateTimeField] = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      if(that.curRow.optFlag == 0) {    //原始状态的标记=2
        that.curRow.optFlag = 2;
      }
      if(that.curRow.startAt && that.curRow.finishAt) {
        that.curRow.num = getFloat(dayjs(that.curRow.finishAt).diff(that.curRow.startAt, "minute") / 60, 1);
      }
    },

    //删除行
    delWorkerFn(index) {
      let that = this;
      if(that.jobDetailData[index].optFlag == 1) {    //新增的可以删除
        that.jobDetailData.splice(index, 1);
      } else {
        that.jobDetailData[index].optFlag = 3;
      }
    },

    //增改详情
    changeTaskDetailFn(confirmFlag) {
      let that = this;

      //清理之前的自动保存
      clearTimeout(that.changeTaskDetailTimer);

      that.jobDetailData.forEach(row => {
        Object.keys(that.taskParams).filter(key => key != "id"  && key != "num").forEach(key => {
          row[key] = that.taskParams[key];
        });
        row.taskId = that.taskParams.id;

        if((!row.finishAt || "" == row.finishAt) && confirmFlag) {
          row.finishAt = dayjs().format("YYYY-MM-DD HH:mm:ss");
          if(row.optFlag == 0) {
            row.optFlag = 2;
          }
        }
      });
      changeTaskDetail(that.jobDetailData.filter(row => row.optFlag != 0), () => {
        that.$toast.success("操作成功");
        setTimeout(() => {
          openWin("odd-job-task");
        }, 2000);
      });
    },

    //加载详情数据
    loadOddJobTaskDetailDataFn() {
      let that = this;
      that.jobDetailData.splice(0, that.jobDetailData.length);
      loadOddJobTaskDetailData({
        taskId: that.taskParams.id
      }, res => {
        res.forEach(row => {
          row.optFlag = 0;
          that.jobDetailData.push(row);
        });
      });
    },

    //检查工作中
    checkInWorkingFn(workerId, callback) {
      let that = this;
      checkInWorking({
        workerId: workerId
      }, res => {
        if(0 != res) {
          that.$toast.fail(res.msg);
        } else {
          callback();
        }
      })
    }
  }
}
</script>

<style lang="scss">
.odd-job-detail {
  margin-top: 5px;
  //导航栏样式
  .van-nav-bar {
    height: 60px;
    .van-icon {
      width: 50px;
      height: 50px;
    }
    .van-nav-bar__right {
      margin-top: 5px;
    }
    .van-button-nav {
      font-size: 28px;
      width: 150px;
    }
  }

  .van-field__label {
    font-size: 22px;
  }
  .van-field__body input {
    font-size: 22px;
    width: 240px;
  }

  //表格样式
  .craft-row {
    border-left: #323233 1px solid;
    line-height: 38px;
    height: 38px;
    &.selected {
      background-color: #e6a23c;
    }
    &.first {
      border-top: #323233 1px solid;
    }
  }
  .craft-row-col {
    text-align: center;
    font-size: large;
    height: 38px;
    overflow: hidden;
    flex: 1;
    border-right: #323233 1px solid;
    border-bottom: #323233 1px solid;
    .van-button {
      height: 38px;
    }
    &.title {
      font-weight: bolder;
    }
    &.dateTime {
      flex: 0 0 240px;
    }
    &.opt {
      display: flex;
      justify-content: center;
      align-items: center;
      button {
        height: 30px;
      }
    }
  }

  //picker选中
  .van-picker-column__item--selected {
    font-size: 26px;
    color: #08936c;
    font-weight: bold;
  }
  //picker取消
  .van-picker__cancel {
    font-size: 26px;
    font-weight: bold;
    color: red;
  }
  //picker确认
  .van-picker__confirm {
    font-size: 26px;
    font-weight: bold;
    color: #001e80;
  }
}
</style>